package com.david.server.rpc;

import java.util.ArrayList;

import javax.servlet.http.HttpSession;

import org.hibernate.Session;

import com.david.client.dto.RoleDTO;
import com.david.client.dto.UserDTO;
import com.david.client.rpc.ILoginService;
import com.david.server.model.User;

public class ILoginServiceImpl extends RemoteService implements ILoginService {
	
	public Integer login(String userName, String password) {
		Session session = getHibernateSession();
		UserDTO userDTO = new UserDTO(userName,password);
		User user = new User(userDTO);
		Integer result = user.login(session);
		
		if(result.intValue()  == SUCCESS){
			HttpSession httpSession = getThreadLocalRequest().getSession();
			session = getHibernateSession();
			session.beginTransaction();
			session.load(userDTO, userDTO.getUserID());
			session.getTransaction().commit();
			httpSession.setAttribute("user", userDTO);
		}
		return result;
	}

	public String[] getRoles() {
		HttpSession httpSession = getThreadLocalRequest().getSession();
//		Session session = getHibernateSession();
		UserDTO userDTO = (UserDTO)httpSession.getAttribute("user");
//		session.beginTransaction();
//		session.update(user);
		Object[] roles = userDTO.getRoles().toArray();
//		session.getTransaction().commit();
		ArrayList list = new ArrayList();
		for(int i = 0; i < roles.length; i ++){
			RoleDTO role = (RoleDTO)roles[i];
			list.add(role.getName());
		}
		return (String[])list.toArray(new String[]{});
	}


}
